<?php
/**
 * Created by PhpStorm.
 * User: 宋春宝
 * Date: 2018/11/1
 * Time: 15:25
 */

namespace app\wchat\controller;


use app\repository\Repository;
use think\Db;
use think\Request;

class Manager extends Common
{
    public function index(){
        return $this->fetch();
    }

    /**
     * 任务列表页面
     * @return mixed
     */
    public function listUI(){
        return $this->fetch('list');
    }

    /**
     * 我的接单
     */
    public function disListUI(){
        return $this->fetch('disList');
    }
    /**
     * 创建工单
     * @return mixed
     */
    public function addWorkUI(){
        return $this->fetch('addWork');
    }

    /**
     * 创建任务页面
     * @return mixed
     */
    public function addDisUI(){
        return $this->fetch('addDis');
    }

    /**
     * 工程师派单
     * @return mixed
     */
    public function sendEnginUI(){
        return $this->fetch('sendEngin');
    }

    /**
     * 团队页面
     */
    public function teamUI(){
        return $this->fetch('team');
    }

    /**
     * 团队添加
     * @return mixed
     */
    public function teamAddUI(){
        return $this->fetch('teamAdd');
    }

    /**
     * 派单任务列表
     * @param Request $request
     * @return array
     */
    public function queryDis(Request $request){
        $input = $request->param();
        $input['gid'] = session('mgid');
        $rows = db('dispatch')->alias('w')->order('w.id desc')->where(function ($query)use($input){

            $query->where('w.reg_id',session('muid'));

            if(!empty($input['id'])){
                $query->where('w.id',$input['id']);
            }

            if(!empty($input['fault_id'])){
                $query->where('w.fault_id',$input['fault_id']);
            }
            if(!empty($input['state_id'])){
                $sis = explode(',',$input['state_id']);
                $query->where('w.state_id','in',$sis);
            }
            if(!empty($input['tel'])){
                $query->where('w.tel',$input['tel']);
            }

            if(!empty($input['key'])){
                $query->where('w.title|ws.number|w.tel','LIKE','%'.$input['key'].'%');
            }

            if(!empty($input['admin_id'])){
                $query->where('w.admin_id',$input['admin_id']);
            }
        })
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username'])
            ->paginate($input['limit'])
            ->toArray();
        return ['code'=>1,'msg'=>'获取成功!','data'=>$rows['data'],'count'=>$rows['total'],'rel'=>1];
    }

    /**
     * 详情页面
     * @return mixed
     */
    public function getDisUI(){

        $id = input('id');

        if(empty($id)){
            $row = db('dispatch')->where('works_id',input('wid'))->field(['id'])->find();
            $id = $row['id'];
        }
        $info = db('dispatch')->alias('w')->where('w.id',$id)
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->join('admin reg','reg.admin_id=w.reg_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username','reg.username as reg_username','reg.name as reg_name'])
            ->find();
        return $this->fetch('getDis',['info'=>$info]);
    }

    /**
     * 故障列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function faults(){
        $rows = db('fault')->order('sort asc')->select();

        $data = [];
        foreach ($rows as $v){
            $data[] = [
                'value'=>$v['title'],
                'id'=>$v['id']
            ];
        }

        return ['code'=>1,'data'=>$data];
    }
    /**
     * 三方单位列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function party(){
        $row = db('admin')->where('group_id',6)->select();
        $data = [];
        foreach ($row as $v){
            $data[] = ['value'=>$v['username'].'('.$v['name'].')','id'=>$v['admin_id']];
        }
        return ['code'=>1,'data'=>$data];
    }

    /**
     * 跟踪
     * @return mixed
     */
    public function trackUI(){
        return $this->fetch('track');
    }

    /**
     * 跟踪列表
     * @param Request $request
     */
    public function track(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];

        $rows = db('dispatch_sheets')->alias('ds')
            ->where('ds.dispatch_id',$did)
            ->join('admin ad','ds.admin_id=ad.admin_id','left')
            ->field(['ds.*','ad.name as admin_name'])->order('ds.id','desc')->select();
        foreach ($rows as &$v){
            $v['list'] = db('dispatch_flow')->alias('df')
                ->where('df.sheet_id',$v['id'])
                ->join('admin ad','ad.admin_id=df.admin_id','left')
                ->field(['df.*','ad.name as admin_name'])->order('id','desc')->select();
        }
        return ['code'=>1,'data'=>$rows];
    }

    /**
     * 接单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function receipt(Request $request)
    {
        $id = $request->param('id');

        $row = db('dispatch')->where('id',$id)->update(['state_id'=>21]);

        if($row){
            $info = db('admin')->where('admin_id',session('muid'))->find();
            $input = [];
            $input['icon']        = "/public/static/wx/img/progress-list/t1.png";
            $input['admin_id']    = session('muid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."已接单";
            $input['step']        = 1;
            db('dispatch_flow')->insert($input);
            $input['icon']        = "/public/static/wx/img/progress-list/t2.png";
            $input['admin_id']    = session('muid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."已组建团队";
            $input['step']        = 2;
            db('dispatch_flow')->insert($input);

            return ['code'=>1,'msg'=>'接单成功'];
        }
        return ['code'=>0,'msg'=>'接单失败'];
    }

    /**
     * 拒单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function refusal(Request $request)
    {
        $id = $request->param('id');
        $val = $request->param('val');
        $row = db('dispatch')->where('id',$id)->update(['state_id'=>23,'reason'=>$val]);
        if($row)
            return ['code'=>1,'msg'=>'信息发送成功'];
        return ['code'=>0,'msg'=>'信息发送失败'];
    }

    /**
     * 派单给组长
     */
    public function toGroup(){
        $ids = \request()->param('ids');//组长ids
        $did = \request()->param('dis_id');//任务id
        if(empty($ids)) return ['code'=>0,'msg'=>'ids参数错误'];
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        $ids = explode(',',$ids);
        $ids = array_filter($ids);
        $ins = [];
        foreach ($ids as $v){
            $ins[] = [
                'dispatch_id'=>$did,
                'admin_id'=>$v,
                'is_lead'=>1
            ];
        }
        $row = db('dispatch_at')->insertAll($ins);
        if($row){
            db('dispatch')->where('id',$did)->update(['is_team'=>1,'state_id'=>25]);
            return ['code'=>1,'msg'=>'操作成功'];
        }

        return ['code'=>0,'msg'=>'操作失败'];
    }

    /**
     * 平台工程师列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function engins(){
        $row = db('admin')->where('group_id',5)->where('is_group',1)->select();
        $data = [];
        foreach ($row as $v){
            $data[] = ['value'=>$v['username'].'('.$v['name'].')','id'=>$v['admin_id'],'is_at'=>$v['is_at']];
        }
        return ['code'=>1,'data'=>$data];
    }

    /**
     * 添加团队人员
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function addTeam(Request $request){
        $did = $request->param('dis_id');
        $aids = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aids)) return ['code'=>0,'msg'=>'aid参数错误'];
        $rule = \app\repository\Dispatch::addTeam($did,$aids);
        if($rule['code']==1){
            $aids = explode(',',$aids);
            $aids = array_filter($aids);
            foreach ($aids as $v){
                db('dispatch_at')->where(['dispatch_id'=>$did,'admin_id'=>$v])->update(['is_lead'=>1]);
            }
        }
        return $rule;
    }

    /**
     * 移除团队人员
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove(Request $request){
        $did = $request->param('dis_id');
        $aid = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aid)) return ['code'=>0,'msg'=>'aid参数错误'];
        return \app\repository\Dispatch::remove($did,$aid);
    }

    /**
     * 任务团队
     * @param Request $request
     * @return array
     */
    public function teamList(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        $rows = db('dispatch_at')->alias('da')
            ->where('da.dispatch_id',$did)
            ->join('admin a','a.admin_id=da.admin_id','left')
            ->join('jobs j','j.id=a.jobs_id','left')
            ->field(['a.*','j.title as jobs_title','da.is_lead','da.is_conf','da.cause','da.apid','da.add_time'])
            ->select();
        $rows = Repository::treeData($rows,0,'apid','admin_id');
        return ['code'=>1,'data'=>$rows];
    }

    /**
     * 工程师列表
     * @param Request $request
     * @return array
     */
    public function query(Request $request){
        $input = $request->param();

        $rows = db('admin')->alias('a')->where(function ($query)use($input){
            $query->where('a.group_id',5);
            $query->where('a.is_part',0);
            $query->where('a.is_group',1);
        })
            ->join('auth_group ag','a.group_id=ag.group_id','left')
            ->join('jobs js','js.id=a.jobs_id','left')
            ->field(['a.*,ag.title','js.title as jobs_title'])
            ->select();
        return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$rows,'rel'=>1];
    }

    /**
     * 创建派单任务
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function addDis(Request $request){
        $input = $request->param();

        $input['state_id'] = 21;

        $msg = $this->validate($input,'app\admin\validate\Dispatch');
        if(!$msg){
            return ['code'=>0,'msg'=>$msg];
        }
        if(!empty($input['works_id'])){

            $info = db('works')->where('id',$input['works_id'])->find();

            if($info['state_id'] >= 12){
                return ['code'=>0,'msg'=>'该工单不可创建任务单'];
            }

            db('works')->where('id',$input['works_id'])->update(['state_id'=>12]);
        }

        $input['number'] = 'D'.date("YmdH",time()).rand(101,999);
        $input['reg_id'] = session('muid');

        $did = db('dispatch')->insertGetId($input);

        if($did)
            return ['code'=>1,'msg'=>'创建成功'];
        return ['code'=>0,'msg'=>'创建失败'];
    }

    /**
     * 编辑工单
     */
    public function editDis(){
        if(\request()->isPost()){
            $input = \request()->only(['id','title','desc','address','name','tel','fault_id']);
            if(empty($input['id'])) return ['code'=>0,'msg'=>'参数错误'];
            $row = db('dispatch')->where('id',$input['id'])->update($input);
            if($row)
                return ['code'=>1,'msg'=>'修改成功'];
            return ['code'=>0,'msg'=>'修改失败'];
        }
        $row = db('dispatch')->alias('dis')
            ->where('dis.id',input('id'))
            ->join('fault ft','ft.id=dis.fault_id','left')
            ->field(['dis.*','ft.title as fault_name'])
            ->find();
        return $this->fetch('edit',['info'=>$row]);
    }

    /**
     * 电厂管理
     * @return mixed
     */
    public function powerUI()
    {
        return $this->fetch('powerList');
    }

    /**
     *  添加
     * @return mixed
     */
    public function powerAddUI()
    {
        return $this->fetch('powerAdd');
    }
    /**
     * @param Request $request
     * @return array
     */
    public function powerList(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        $rows = db('power')->alias('da')
            ->where('da.dispatch_id',$did)
            ->join('admin a','a.admin_id=da.admin_id','left')
            ->join('jobs j','j.id=a.jobs_id','left')
            ->field(['a.*','j.title as jobs_title','da.forever','da.expire'])
            ->select();
        return ['code'=>1,'data'=>$rows];
    }

    public function removePower(Request $request){
        $did = $request->param('dis_id');
        $aid = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aid)) return ['code'=>0,'msg'=>'aid参数错误'];
        $cs = db('power')->where(['dispatch_id'=>$did,'admin_id'=>$aid])->delete();
        if($cs)
            return ['code'=>1,'msg'=>'移除成功'];
        return ['code'=>0,'msg'=>'移除失败'];
    }

    public function powerQuery(){
        $rows = db('admin')->where(function ($query){
            $query->where('group_id',10);
            $query->where('a_pid',session('muid'));
        })
            ->field(['admin_id','name','username'])
            ->select();
        return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$rows,'rel'=>1];
    }

    public function powerAdd(Request $request)
    {
        $did = $request->param('dis_id');
        $aids = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aids)) return ['code'=>0,'msg'=>'aid参数错误'];
        $aids = explode(',',$aids);
        $aids = array_filter($aids);
        $input = [];
        foreach ($aids as $v){
            $input[] = [
                'dispatch_id'=>$did,
                'admin_id'=>$v,
                'belo_id'=>session('muid'),
                'forever'=>1
            ];
        }
        $cs = db('power')->insertAll($input);
        if($cs)
            return ['code'=>1,'msg'=>'操作成功'];
        return ['code'=>0,'msg'=>'操作失败'];
    }

    /**
     * 电厂管理
     * @return mixed
     */
    public function elecUI(){
        return $this->fetch('elec');
    }

    /**
     * 删除账户
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delPower(Request $request){
        $aid = $request->param('aid');
        $did = db('admin')->where(['admin_id'=>$aid,'a_pid'=>session('muid')])->delete();
        if($did){
            db('power')->where('admin_id',$aid)->delete();
            return ['code'=>1,'msg'=>'删除成功'];
        }
        return ['code'=>0,'msg'=>'删除失败'];
    }

    public function addPower(Request $request){
        $input = $request->param();
        $ins = [
            'username'=>$input['tel'],
            'tel'=>$input['tel'],
            'name'=>$input['name'],
            'pwd'=>$input['pwd'],
            'group_id'=>10,
            'is_open'=>$input['is_open'],
            'add_time'=>time(),
            'a_pid'=>session('muid'),
        ];
        if($ins['pwd'] == $input['qpwd']){
            $ins['pwd'] = md5($ins['pwd']);
        }else{
            return ['code'=>0,'密码不一致'];
        }
        $ns = db('admin')->where('username|tel',$input['tel'])->count();
        if($ns>0){
            return ['code'=>0,'msg'=>'手机号码已被注册'];
        }
        $id = db('admin')->insertGetId($ins);
        if($id)
            return ['code'=>1,'msg'=>'注册成功'];
        return ['code'=>0,'msg'=>'注册失败'];
    }

    public function editPower(Request $request){
        $input = $request->param();
        if(empty($input['admin_id'])) return ['code'=>0,'msg'=>'参数错误'];
        $ins = [
            'username'=>$input['tel'],
            'tel'=>$input['tel'],
            'name'=>$input['name'],
            'is_open'=>$input['is_open'],
        ];
        if(!empty($input['pwd'])){
            if($ins['pwd'] == $input['qpwd']){
                $ins['pwd'] = md5($ins['pwd']);
            }else{
                return ['code'=>0,'密码不一致'];
            }
        }
        $ns = db('admin')->where('username|tel',$input['tel'])->where('admin_id','<>',$input['admin_id'])->count();
        if($ns>0){
            return ['code'=>0,'msg'=>'手机号码已被注册'];
        }
        $id = db('admin')->where('admin_id',$input['admin_id'])->update($ins);
        if($id)
            return ['code'=>1,'msg'=>'修改成功'];
        return ['code'=>0,'msg'=>'修改失败'];
    }

    public function addPowerUI(){
        return $this->fetch('addPower');
    }

    public function editPowerUI(){
        $id = \request()->param('id');
        $info = db('admin')->where(['admin_id'=>$id,'a_pid'=>session('muid')])->find();
        return $this->fetch('editPower',['info'=>$info]);
    }

    /**
     * 完成工单
     */
    public function complete(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return json(['code'=>0,'msg'=>'参数错误，请返回重新提交']);
        $input = [
            'id'=>$did,
            'state_id'=>24
        ];
        $row = db('dispatch')->where('id',$input['id'])->update($input);
        if($row){
            $team = db('dispatch_at')->where('dispatch_id',$did)->select();
            $ids_arr = [];
            foreach ($team as $v){
                $ids_arr[] = $v['admin_id'];
            }
            db('admin')->where('admin_id','in',$ids_arr)->update(['is_at'=>0]);
            return json(['code'=>1,'msg'=>'信息提交成功']);
        }
        return json(['code'=>0,'msg'=>'信息提交失败']);
    }
}